package me.jiatao.jetpack;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import org.reactivestreams.Publisher;

import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import me.jiatao.jetpack.room.Book;
import me.jiatao.jetpack.room.BookDao;
import me.jiatao.jetpack.room.User;
import me.jiatao.jetpack.room.UserDao;
import me.jiatao.jetpack.room.UserDatabase;

public class RoomActivity extends AppCompatActivity {
    private static final String TAG = "***RoomActivity***";
    private UserDao mUserDao;
    private BookDao mBookDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room);
        UserDatabase userDatabase = UserDatabase.getInstance(getApplicationContext());
        mUserDao = userDatabase.getUserDao();
        mBookDao = userDatabase.getBookDao();
    }

    int currIndex = -1;

    public void insertUser(View view) {
        ++currIndex;
        User user = new User();
        user.setFirstName("tao->" + currIndex);
        user.setLastName("jia->" + currIndex);

        mUserDao.insertAll(user);
    }

    public void deleteUser(View view) {
        User user = new User();
        //user.setUid(1);
        user.setFirstName("tao->" + 1);
        user.setLastName("jia->" + 1);

        int deleteCount = mUserDao.delete(user);
        Log.i(TAG, "deleteCount--->" + deleteCount);
    }

    @SuppressLint("CheckResult")
    public void getAllUser(View view) {
        mUserDao.getAllUser()
                .flatMap(new Function<List<User>, Publisher<User>>() {
                    @Override
                    public Publisher<User> apply(List<User> users) throws Exception {
                        return Flowable.fromIterable(users);
                    }
                })
                .subscribe(new Consumer<User>() {
                    @Override
                    public void accept(User user) throws Exception {
                        Log.i(TAG, user.toString());
                    }
                });
    }

    public void insertBook(View view) {
        Book book = new Book();
        for (int i = 1; i < 6; i++) {
            book.title = "book" + i;
            book.userId = i;
            mBookDao.insertAll(book);
        }
        book.title = "book6";
        book.userId = 1;
        mBookDao.insertAll(book);

    }

    public void deleteBook(View view) {
    }

}
